<!DOCTYPE html>





<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/CNY32x32.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/CNY16x16.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":true},
    save_scroll: false,
    copycode: {"enable":true,"show_result":true,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="概述定义JAVA反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。功能 运行时判断任意一个对象所属的类  运行时构造任一个类的对象  运行时判断任意一个类的成员变量和方法  运行时调用任意一个对象的成员变量和方法  动态代理（反射的关键应用）">
<meta property="og:type" content="article">
<meta property="og:title" content="反射学习笔记">
<meta property="og:url" content="localhost:4000/2020/01/01/反射学习笔记/index.html">
<meta property="og:site_name" content="钟浩伟的个人博客">
<meta property="og:description" content="概述定义JAVA反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。功能 运行时判断任意一个对象所属的类  运行时构造任一个类的对象  运行时判断任意一个类的成员变量和方法  运行时调用任意一个对象的成员变量和方法  动态代理（反射的关键应用）">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-01-01T09:55:09.921Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="反射学习笔记">
<meta name="twitter:description" content="概述定义JAVA反射机制是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。功能 运行时判断任意一个对象所属的类  运行时构造任一个类的对象  运行时判断任意一个类的成员变量和方法  运行时调用任意一个对象的成员变量和方法  动态代理（反射的关键应用）">
  <link rel="canonical" href="localhost:4000/2020/01/01/反射学习笔记/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>反射学习笔记 | 钟浩伟的个人博客</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">钟浩伟的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">欢迎光临</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    
  <div class="popup search-popup">
  <div class="search-header">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <div class="search-input-wrapper">
      <input autocomplete="off" autocorrect="off" autocapitalize="none"
             placeholder="搜索..." spellcheck="false"
             type="text" id="search-input">
    </div>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>
  <div id="search-result"></div>
</div>


  </div>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="localhost:4000/2020/01/01/反射学习笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="钟浩伟">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/profile.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="钟浩伟的个人博客">
    </span>
      <header class="post-header">

        
          <h1 class="post-title" itemprop="name headline">反射学习笔记

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2020-01-01 12:08:14" itemprop="dateCreated datePublished" datetime="2020-01-01T12:08:14+08:00">2020-01-01</time>
            </span>
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><p><a href="https://baike.baidu.com/item/JAVA反射机制/6015990" target="_blank" rel="noopener">JAVA反射机制</a>是在运行状态中，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意方法和属性；这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。</p><h2 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h2><ol>
<li><p>运行时判断任意一个对象所属的类</p>
</li>
<li><p>运行时构造任一个类的对象</p>
</li>
<li><p>运行时判断任意一个类的成员变量和方法</p>
</li>
<li><p>运行时调用任意一个对象的成员变量和方法</p>
</li>
<li><p>动态代理（反射的关键应用）</p>
</li>
</ol><a id="more"></a>

<h2 id="主要API"><a href="#主要API" class="headerlink" title="主要API"></a>主要API</h2><table>
<thead>
<tr>
<th>类名</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td>Class类</td>
<td>代表类的实体，在运行的Java应用程序中表示类和接口</td>
</tr>
<tr>
<td>Field类</td>
<td>代表类的成员变量（成员变量也称为类的属性）</td>
</tr>
<tr>
<td>Method类</td>
<td>代表类的方法</td>
</tr>
<tr>
<td>Constructor类</td>
<td>代表类的构造的构造方法</td>
</tr>
</tbody></table>
<h3 id="Class类"><a href="#Class类" class="headerlink" title="Class类"></a>Class类</h3><p>在Object类中定义了getClass()方法，这个方法被所有子类继承</p>
<p><em>public final Class getClass()</em></p>
<h4 id="实例化Class类对象的四种方法"><a href="#实例化Class类对象的四种方法" class="headerlink" title="实例化Class类对象的四种方法"></a>实例化Class类对象的四种方法</h4><ol>
<li><p>通过类名创建</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class clazz = String.class;</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过实例创建</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class clazz = <span class="string">"www.xyz.com"</span>.getClass(); <span class="comment">//通过String对象创建</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>通过类的全类名创建</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class clazz = Class.forName(<span class="string">"java.lang.String"</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过类加载器创建</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ClassLoader cl = <span class="keyword">this</span>.getClass().getClassLoader();</span><br><span class="line">Class clazz = cl.loadClass(<span class="string">"全类名"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h3 id="Class对象的常见方法"><a href="#Class对象的常见方法" class="headerlink" title="Class对象的常见方法"></a>Class对象的常见方法</h3><p><strong>类相关：</strong></p>
<table>
<thead>
<tr>
<th>方法</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td>getName()</td>
<td>获得类的完整路径名字</td>
</tr>
<tr>
<td>getSimpleName()</td>
<td>获得类的名字</td>
</tr>
<tr>
<td>getSuperclass()</td>
<td>获得当前类继承的父类的名字</td>
</tr>
<tr>
<td>getInterfaces()</td>
<td>获得当前类实现的类或是接口</td>
</tr>
<tr>
<td>newInstance()</td>
<td>创建类的实例，无参，返回Object，需要强转</td>
</tr>
</tbody></table>
<p>如果需要创建一个有参实例，先获取有参的构造函数，在通过newIntsance()创建；</p>
<p><strong>构造器相关：</strong></p>
<table>
<thead>
<tr>
<th>方法</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td>getConstructors()</td>
<td>获得该类的所有公有构造方法</td>
</tr>
<tr>
<td>getConstructor(Class…&lt;?&gt; parameterTypes)</td>
<td>获得该类中与参数类型匹配的公有构造方法</td>
</tr>
<tr>
<td>getDeclaredConstructors()</td>
<td>获得该类所有构造方法</td>
</tr>
<tr>
<td>getDeclaredConstructor(Class…&lt;?&gt; parameterTypes)</td>
<td>获得该类中与参数类型匹配的构造方法</td>
</tr>
</tbody></table>
<p>通过反射机制，强制调用私有构造函数创建对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Constructor c = clazz.getDeclaredConstructors(String.class);</span><br><span class="line">c.setAccessible(<span class="keyword">true</span>);<span class="comment">//解除私有封装</span></span><br><span class="line">Object ob = c.newInstance(<span class="string">"Hello"</span>);</span><br></pre></td></tr></table></figure>

<p><strong>方法相关：</strong></p>
<table>
<thead>
<tr>
<th>方法</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td>getDeclaredMethods()</td>
<td>返回此Class对象所表示的类或接口的全部方法</td>
</tr>
<tr>
<td>getMethods()</td>
<td>返回此Class对象所表示的类或接口的public方法</td>
</tr>
</tbody></table>
<p>通过反射调用特定方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Method m = clazz.getMethod(name,params);</span><br><span class="line">m.invoke(obj,args);<span class="comment">//obj是实例化的对象，args是实参</span></span><br></pre></td></tr></table></figure>

<p>如果需要调用一个私有方法需要加上</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">m.setAccessible(<span class="keyword">true</span>);</span><br></pre></td></tr></table></figure>

<p>调用有返回值的方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Method m = clazz.getMethod(name,params);</span><br><span class="line">Object c =m.invoke(obj,args);</span><br></pre></td></tr></table></figure>

<p><strong>属性相关：</strong></p>
<table>
<thead>
<tr>
<th>方法</th>
<th>用途</th>
</tr>
</thead>
<tbody><tr>
<td>getFields()</td>
<td>返回此Class对象所表示的类或接口的public属性</td>
</tr>
<tr>
<td>getDelcaredFields()</td>
<td>返回此Class对象所表示的类或接口的全部Field</td>
</tr>
</tbody></table>
<p>通过反射调用属性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Constructor con = clazz.getConstructor();</span><br><span class="line">Student stu = (Student)con.newInstance();</span><br><span class="line">Field f = clazz.getField(<span class="string">"school"</span>);</span><br><span class="line">f.set(stu,<span class="string">"第一中学"</span>); <span class="comment">//设置属性</span></span><br><span class="line">String school = (String)f.get(stu); <span class="comment">//获取属性</span></span><br></pre></td></tr></table></figure>

<p>通过反射调用私有属性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Field f = clazz.getDeclaredField(<span class="string">"privateField"</span>);</span><br><span class="line">f.setAccessible(<span class="keyword">true</span>); <span class="comment">//解除私有封装</span></span><br><span class="line">f.set(stu,<span class="string">"私有属性"</span>);</span><br><span class="line">String field = (String)f.get(stu);</span><br></pre></td></tr></table></figure>

<h3 id="Constructor类"><a href="#Constructor类" class="headerlink" title="Constructor类"></a>Constructor类</h3><p><a href="https://developer.android.google.cn/reference/java/lang/reflect/Constructor" target="_blank" rel="noopener">文档</a></p>
<h3 id="Method类"><a href="#Method类" class="headerlink" title="Method类"></a>Method类</h3><p><a href="https://developer.android.google.cn/reference/java/lang/reflect/Method" target="_blank" rel="noopener">文档</a></p>
<h3 id="Field类"><a href="#Field类" class="headerlink" title="Field类"></a>Field类</h3><p><a href="https://developer.android.google.cn/reference/java/lang/reflect/Field" target="_blank" rel="noopener">文档</a></p>
<p>public int getModifiers() 以整数形式返回此Field的修饰符</p>
<p>public Class&lt;?&gt; getType() 得到Field的属性类型</p>
<p>public String getName() 返回Field的名称</p>
<h1 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h1><p>考虑下需求：</p>
<p>某一开发人员，假设它会java和C++两种语言，但是由于这两种语言难度不同，所以他掉的头发也会不同。所以在他写代码之前，他都会祈祷让自己的头发少掉一点，所以如何在真正写代码前完成这样一个祈祷并告知发量的程序呢，利用动态代理即可。</p>
<p>先定义一个Java接口，表示码农</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Coder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">codeJava</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">codeCPlusPlus</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后写出该接口的一个实现类，表示某一个具体的码农</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Developer</span> <span class="keyword">implements</span> <span class="title">Coder</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">codeJava</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"System.out.println(\"Hello,World\");"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">codeCPlusPlus</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"cout &lt;&lt; \"Hello, world!\";"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后插入动态代理，在执行方法前，完成告知发量状况</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Coding</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Developer zhong = <span class="keyword">new</span> Developer();</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 匿名类实现</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        Coder zhongProxy = (Coder)Proxy.newProxyInstance(zhong.getClass().getClassLoader(),zhong.getClass().getInterfaces(),</span><br><span class="line">                ((proxy, method, args1) -&gt; &#123;</span><br><span class="line">                    <span class="keyword">if</span>(method.getName().equals(<span class="string">"codeJava"</span>))&#123;</span><br><span class="line">                        System.out.println(<span class="string">"coding Java...Hair reduce 30%"</span>);</span><br><span class="line">                    &#125;<span class="keyword">else</span> <span class="keyword">if</span> (method.getName().equals(<span class="string">"codeCPlusPlus"</span>))&#123;</span><br><span class="line">                        System.out.println(<span class="string">"coding C++...Hair reduce 60%"</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                    Object result = method.invoke(zhong, args);</span><br><span class="line">                    System.out.println(<span class="string">"coding done!"</span>);</span><br><span class="line">                    <span class="keyword">return</span> result;</span><br><span class="line">                &#125;));</span><br><span class="line">        zhongProxy.codeJava();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"========================================================================="</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">coding Java...Hair reduce <span class="number">30</span>%</span><br><span class="line">System.out.println(<span class="string">"Hello,World"</span>);</span><br><span class="line">coding done!</span><br></pre></td></tr></table></figure>

<p>上述这种方式采用了匿名类实现，更加简洁，如果喜欢麻烦，可以使用下面这种方式</p>
<p>创建码农代理类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.InvocationHandler;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DevelopProxy</span> <span class="keyword">implements</span> <span class="title">InvocationHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Object object;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DevelopProxy</span><span class="params">(Object object)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.object = object;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(method.getName().equals(<span class="string">"codeJava"</span>))&#123;</span><br><span class="line">            System.out.println(<span class="string">"coding Java...Hair reduce 30%"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(method.getName().equals(<span class="string">"codeCPlusPlus"</span>))&#123;</span><br><span class="line">            System.out.println(<span class="string">"coding C++...Hair reduce 60%"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        Object result = method.invoke(object, args);</span><br><span class="line">        System.out.println(<span class="string">"coding done!"</span>);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样，在main方法中调用Proxy.newInstance即可</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Coding</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Developer zhong = <span class="keyword">new</span> Developer();</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 老老实实写接口类实现</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">        zhongProxy = (Coder)Proxy.newProxyInstance(zhong.getClass().getClassLoader(),zhong.getClass().getInterfaces(),<span class="keyword">new</span> DevelopProxy(zhong));</span><br><span class="line">        zhongProxy.codeCPlusPlus();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果：</p>
<p>coding C++…Hair reduce 60%<br>cout &lt;&lt; “Hello, world!”;<br>coding done!</p>

    </div>

    
    
    
      


    
    <div>
      
      <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束感谢您的阅读,如有疑问，请联系<a href="mailto:610596547@qq.com">610596547@qq.com</a>-------------</div>
    
</div>
      
    </div>
        
      

      <footer class="post-footer">

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/12/26/Spring Cloud笔记/" rel="next" title="Spirng Cloud学习笔记">
                  <i class="fa fa-chevron-left"></i> Spirng Cloud学习笔记
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2020/01/11/vue父子组件双向数据绑定/" rel="prev" title="vue父子组件双向数据绑定">
                  vue父子组件双向数据绑定 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/profile.jpg"
      alt="钟浩伟">
  <p class="site-author-name" itemprop="name">钟浩伟</p>
  <div class="site-description motion-element" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">44</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">15</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/XiaoZhong233" title="GitHub &rarr; https://github.com/XiaoZhong233" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:601596547@qq.com" title="E-Mail &rarr; mailto:601596547@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://blog.csdn.net/weixin_41154636" title="CSDN &rarr; https://blog.csdn.net/weixin_41154636" rel="noopener" target="_blank"><i class="fa fa-fw fa-book"></i>CSDN</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="http://profile.zhonghaowei.xyz/" title="Profile &rarr; http://profile.zhonghaowei.xyz/" rel="noopener" target="_blank"><i class="fa fa-fw fa-address-card-o"></i>Profile</a>
      </span>
    
  </div>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#定义"><span class="nav-number">1.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#功能"><span class="nav-number">1.2.</span> <span class="nav-text">功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#主要API"><span class="nav-number">1.3.</span> <span class="nav-text">主要API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Class类"><span class="nav-number">1.3.1.</span> <span class="nav-text">Class类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实例化Class类对象的四种方法"><span class="nav-number">1.3.1.1.</span> <span class="nav-text">实例化Class类对象的四种方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Class对象的常见方法"><span class="nav-number">1.3.2.</span> <span class="nav-text">Class对象的常见方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Constructor类"><span class="nav-number">1.3.3.</span> <span class="nav-text">Constructor类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Method类"><span class="nav-number">1.3.4.</span> <span class="nav-text">Method类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Field类"><span class="nav-number">1.3.5.</span> <span class="nav-text">Field类</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#动态代理"><span class="nav-number">2.</span> <span class="nav-text">动态代理</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      



    </div>
  </aside>
  <div id="sidebar-dimmer"></div>




      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钟浩伟</span>
</div>


<div id="days"></div>
<div class="BbeiAn-info">
   	粤ICP备 -
    <a target="_blank" href="http://beian.miit.gov.cn" style="color:#f0d784"  rel="nofollow">粤ICP备19111001号-1</a> <!--a标签中增加nofollow属性，避免爬虫出站。-->| 
	<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=" style="color:#f0d784;text-decoration:none;padding-left:30px;background:url(https://s1.ax1x.com/2018/09/29/ilmwIH.png) no-repeat left center" rel="nofollow">粤公网安备 粤ICP备19111001号-1</a>	  <!--这里将图标作为了背景，以使得能和后面的文字在同一行-->
</div>

<script>
function show_date_time(){
    window.setTimeout("show_date_time()", 1000);
    BirthDay=new Date("08/15/2019 22:40:14");
    today=new Date();
    timeold=(today.getTime()-BirthDay.getTime());
    sectimeold=timeold/1000
    secondsold=Math.floor(sectimeold);
    msPerDay=24*60*60*1000
    e_daysold=timeold/msPerDay
    daysold=Math.floor(e_daysold);
    e_hrsold=(e_daysold-daysold)*24;
    hrsold=setzero(Math.floor(e_hrsold));
    e_minsold=(e_hrsold-hrsold)*60;
    minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
    seconds=setzero(Math.floor((e_minsold-minsold)*60));
    document.getElementById('days').innerHTML="<p>小破站已运行 "+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒</p>";
}
function setzero(i) {
    if (i<10) {
        i="0" + i
    };
    return i;
}
show_date_time();
</script>

        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>

<script src="/js/schemes/pisces.js?v=7.3.0"></script>



<script src="/js/next-boot.js?v=7.3.0"></script>




  















  <script src="/js/local-search.js?v=7.3.0"></script>










<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'default',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>




  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>



  
  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false}});</script></body>
</html>
